<!-- 选择联系人弹窗 -->
<template>
  <el-dialog
    v-model="dialogFormVisible"
    title="选择人员"
    width="70%"
    draggable
    overflow
    @close="handleClose"
  >
    <div class="crossRope" />
    <el-form style="margin-top: 2%">
      <el-row>
        <!-- 左侧树形图 -->
        <el-col :span="8">
          <div class="tree-container">
            <el-tree
              :data="rootNodes"
              :props="defaultProps"
              node-key="id"
              :load="loadNode"
              lazy
              :expand-on-click-node="false"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span @click="handleNodeClick(data)">
                    {{ data.deptName }}
                  </span>
                  <el-button
                    v-if="data.hasChildren"
                    type="text"
                    size="small"
                    @click.stop="node.expand()"
                  >
                    展开
                  </el-button>
                </span>
              </template>
            </el-tree>
          </div>
        </el-col>
        <!-- 右侧表单 -->
        <el-col :span="16">
          <el-form>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系人姓名" style="width: 80%">
                  <el-input
                    v-model="searchForm.realName"
                    size="small"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-button
                  :icon="Search"
                  color="#1E3485"
                  size="small"
                  @click="
                    tablePage.currentPage = 1;
                    getList(true);
                  "
                  >搜索</el-button
                >
                <el-button :icon="Delete" size="small" @click="clearInput()"
                  >清空</el-button
                >
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <vxe-table
                  ref="xTable"
                  border
                  min-height="350"
                  max-height="550"
                  header-align="center"
                  :column-config="{ resizable: true }"
                  :row-config="{ isHover: true }"
                  :data="contactTableData"
                  size="mini"
                  :loading="tableLoading"
                  :pager-config="tablePage"
                >
                  <vxe-column type="checkbox" width="60" align="center" />
                  <vxe-column
                    type="seq"
                    title="序号"
                    width="50"
                    align="center"
                  />
                  <vxe-column
                    v-for="column in contactTableColumns"
                    :key="column.field"
                    :field="column.field"
                    :title="column.title"
                    :min-width="column.width"
                    align="center"
                    show-overflow
                  >
                    <template v-slot:default="{ row }">
                      {{ row[column.field] }}
                    </template>
                  </vxe-column>
                </vxe-table>
                <vxe-pager
                  v-model:current-page="tablePage.currentPage"
                  v-model:page-size="tablePage.pageSize"
                  :layouts="[
                    'Sizes',
                    'PrevJump',
                    'PrevPage',
                    'Number',
                    'NextPage',
                    'NextJump',
                    'FullJump',
                    'Total'
                  ]"
                  :total="tablePage.total"
                  size="mini"
                  style="margin-top: 2%"
                  @page-change="handlePageChange"
                />
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-form>
    <div class="crossRope" />
    <div style="text-align: right; margin-top: 2%">
      <el-button
        color="#1E3485"
        :icon="Select"
        size="small"
        @click="selectConfirm"
        >确定</el-button
      >
      <el-button :icon="CloseBold" size="small" @click="handleClose"
        >关闭</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElDialog, ElMessage, ElTree } from "element-plus";
import { Delete, Search, Select, CloseBold } from "@element-plus/icons-vue";
import { VxePagerEvents } from "vxe-table";
import type { OrgNode } from "@/views/ERP_sales/type/sales_type";
import { getOrgList, getOrgMenberList } from "@/api/ERP_sales";

// 弹窗关闭/打开事件
const props = defineProps({
  visible: Boolean,
  projectId: String
});
const dialogFormVisible = ref(false);
const emit = defineEmits(["close", "confirm"]);
function handleClose() {
  emit("close", false);
}
watch(
  () => props.visible,
  val => {
    dialogFormVisible.value = val;
  },
  { immediate: true }
);

// 搜索表单
let searchForm = reactive({
  realName: "",
  deptId: "1"
});
// 清空按钮
function clearInput() {
  searchForm.realName = "";
}

// 表格配置
let contactTableData = ref([]);
let tableLoading = ref(false);
let xTable = ref(null);
// const selectedRow = ref(null as any);
const contactTableColumns = ref([
  {
    field: "userName",
    title: "登录账户",
    width: 100
  },
  {
    field: "realName",
    title: "姓名",
    width: 100
  },
  {
    field: "sex",
    title: "性别",
    width: 60
  },
  {
    field: "phone",
    title: "手机号",
    width: 120
  },
  {
    field: "roleName",
    title: "所属岗位",
    width: 120
  }
]);
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};
// 获取选中行
function getSelectedRows() {
  return xTable.value.getCheckboxRecords();
}
// 获取表格数据
async function getList(search?: boolean) {
  tableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  params.deptId = searchForm.deptId;
  if (search) {
    params.realName = searchForm.realName;
  }
  try {
    const response: ApiResponse = await getOrgMenberList(params);
    contactTableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  } catch (error) {
    ElMessage.error("获取表格数据失败");
  } finally {
    tableLoading.value = false;
  }
}

// 左侧树形图
const defaultProps = {
  children: "children",
  label: "deptName"
};
const rootNodes = ref<OrgNode[]>([]);
const loadNode = async (node: any, resolve: Function) => {
  const nodeId = node.data.id;
  const childrenData = await getTreeList(nodeId);
  resolve(childrenData);
};
// 获取数据
async function getTreeList(parentId?: string): Promise<OrgNode[]> {
  let params: ApiParams = {};
  if (parentId) {
    params = { parentId };
  }
  const response: ApiResponse = await getOrgList(params);
  if (response.code === 200) {
    return response.data.map((item: any) => ({
      id: item.id,
      deptName: item.deptName,
      parentId: item.parentId,
      hasChildren: item.hasChildren,
      children: []
    }));
  }
  throw new Error(response.msg);
}
// 树形图点击事件
function handleNodeClick(data: any) {
  searchForm.deptId = data.id;
  getList();
}

// 确认事件
function selectConfirm() {
  if (getSelectedRows().length === 0) {
    ElMessage.error("请选择一条数据");
  } else {
    let idList = [];
    for (let i = 0; i < getSelectedRows().length; i++) {
      idList.push(getSelectedRows()[i].id);
    }
    emit("confirm", {
      projectId: props.projectId,
      idList: idList
    });
    // 关闭弹窗
    handleClose();
  }
}

// 打开弹窗时执行
watch(dialogFormVisible, newValue => {
  if (newValue) {
    getList();
  }
});
</script>

<style lang="scss" scoped>
.tree-container {
  max-height: 450px;
  overflow-y: auto;
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
}
</style>
